﻿using CefSharp;
using System;
using System.Collections.Generic;
using System.Text;

namespace CodeGenerateEngine.Handlers
{
    internal class MenuHandler : IContextMenuHandler
    {
        private const int ShowDevTools = 26501;
        private const int CloseDevTools = 26502;
        private const int IframeReload = 26506;

        public Func<IWebBrowser, IBrowser, IFrame, IContextMenuParams, IMenuModel, bool> onBeforeContextMenu;

        void IContextMenuHandler.OnBeforeContextMenu(IWebBrowser browserControl, IBrowser browser, IFrame frame, IContextMenuParams parameters, IMenuModel model)
        {
            if (onBeforeContextMenu != null)
            {
                if (onBeforeContextMenu.Invoke(browserControl, browser, frame, parameters, model) == false)
                {
                    return;
                }
            }
            model.AddItem(CefMenuCommand.Reload, "重新加载");
            model.AddItem((CefMenuCommand)ShowDevTools, "审查元素");
            if (!frame.IsMain)
            {
                model.AddSeparator();
                model.AddItem((CefMenuCommand)IframeReload, "重新加载框架");
            }
        }

        bool IContextMenuHandler.OnContextMenuCommand(IWebBrowser browserControl, IBrowser browser, IFrame frame, IContextMenuParams parameters, CefMenuCommand commandId, CefEventFlags eventFlags)
        {
            if ((int)commandId == ShowDevTools)
            {
                browser.ShowDevTools();
            }
            else if ((int)commandId == IframeReload)
            {
                //frame.LoadUrl(frame.Url);
                frame.EvaluateScriptAsync("window.location.reload();");
                //frame.Browser.Reload();
            }
            return false;
        }

        void IContextMenuHandler.OnContextMenuDismissed(IWebBrowser browserControl, IBrowser browser, IFrame frame)
        {

        }

        bool IContextMenuHandler.RunContextMenu(IWebBrowser browserControl, IBrowser browser, IFrame frame, IContextMenuParams parameters, IMenuModel model, IRunContextMenuCallback callback)
        {
            return false;
        }

        public static MenuHandler ClearMenuHandler()
        {
            var menuHandler = new MenuHandler();
            menuHandler.onBeforeContextMenu = (IWebBrowser browserControl, IBrowser browser, IFrame frame, IContextMenuParams parameters, IMenuModel model) =>
            {
                model.Clear();
                return false;
            };
            return menuHandler;
        }
    }
}
